//
//  JCCamyListViewController.swift
//  JCNewsForMac
//
//  Created by ifly on 24/7/18.
//  Copyright © 2018年 Ismail. All rights reserved.
//

import Cocoa
import SwiftyJSON
import Kingfisher


class JCCamyListViewController: NSViewController {
    
    private var jcType = 1
    private var jcState = 1

    //MARK:最根部的NSSplitView
    private lazy var jcSplitView:NSSplitView = {
        
        var jcSplitView = NSSplitView.init(frame: self.view.frame)
        jcSplitView.isVertical = true
        jcSplitView.dividerStyle = .thick
        jcSplitView.delegate = self
        
        return jcSplitView
    }()

    //    MARK:左边的背景view
    private lazy var jcLeftView:NSView = {
        var leftView = NSView.init(frame: CGRect.init(x: 0, y: 0, width: 300, height: self.view.frame.size.height))
        leftView.wantsLayer = true
        leftView.layer?.backgroundColor = NSColor.white.cgColor
        return leftView
    }()
    
    //    MARK: 类型选择框
    private lazy var jcTypeComboBox:NSComboBox = {
        
        var jcTypeComboBox = NSComboBox.init(frame: CGRect.init(x: 5, y: self.view.frame.size.height - 45, width: 130, height: 32))
        jcTypeComboBox.isEditable = false
        jcTypeComboBox.numberOfVisibleItems = 5
        jcTypeComboBox.addItems(withObjectValues: ["供应商","分销商"])
        jcTypeComboBox.selectItem(withObjectValue: "供应商")
        jcTypeComboBox.font = NSFont.systemFont(ofSize: 16)
        jcTypeComboBox.tag = 100
        jcTypeComboBox.delegate = self

        return jcTypeComboBox;
    }()
    //    MARK:状态选择框
    private lazy var jcStateComboBox:NSComboBox = {
        var jcStateComboBox = NSComboBox.init(frame: CGRect.init(x: 150, y: self.view.frame.size.height - 45, width: 130, height: 35))
        jcStateComboBox.isEditable = false
        jcStateComboBox.numberOfVisibleItems = 5
        jcStateComboBox.addItems(withObjectValues: ["被驳回","已通过","审核中"])
        jcStateComboBox.selectItem(withObjectValue: "审核中")
        jcStateComboBox.font = NSFont.systemFont(ofSize: 16)
        jcStateComboBox.tag = 101
        jcStateComboBox.delegate = self
        return jcStateComboBox;
    }()
    
    //   MARK:NSSplitView 左边部分 NSScrollView
    private lazy var jcLeftScrView:NSScrollView = {
//        定义ScrollView，NSTableView的滑动必须依附在ScrollView上
        var jcLeftScrView = NSScrollView.init(frame: CGRect.init(x: 0, y: 0, width: 300, height: self.view.frame.size.height - 40))
        jcLeftScrView.drawsBackground = true
        jcLeftScrView.hasVerticalScroller = true
        jcLeftScrView.autohidesScrollers = true
        return jcLeftScrView
    }()
    //    MARK:定义 NSTableView
    private lazy var rootabelview:NSTableView = {
        
        var rootabelview = NSTableView.init(frame: self.view.frame)
        rootabelview.focusRingType = NSFocusRingType.default//tableview获得焦点时的风格
        rootabelview.selectionHighlightStyle = .regular //行高亮的风格
        rootabelview.backgroundColor  = NSColor.orange
        rootabelview.usesAlternatingRowBackgroundColors = true //背景颜色的交替，一行白色，一行灰色。设置后，原来设置的 backgroundColor 就无效了。
        rootabelview.delegate = self
        rootabelview.dataSource = self
        rootabelview.gridColor = NSColor.magenta
        rootabelview.rowHeight = 60
        rootabelview.frame = self.view.bounds
        rootabelview.headerView? = NSTableHeaderView()
        
        return rootabelview
    }()
    
    //   MARK:NSSplitView的右边部分 NSView
    private lazy var jcRightView:NSView = {
        var rigtView = NSView.init(frame: CGRect.init(x: 0, y: 0, width: 760, height: self.view.frame.size.height))
        return rigtView
    }()
    
    private lazy var jcRightScrView:NSScrollView = {
        
        var jcRightScrView = NSScrollView.init(frame: CGRect.init(x: 0, y: 100, width: 760, height: self.view.frame.size.height - 100))
        return jcRightScrView
    }()
    
    private lazy var jcCollectionView: NSCollectionView = {
        
        let flowLayout = NSCollectionViewFlowLayout.init()
        flowLayout.scrollDirection = .vertical  // 设置排列方式
        flowLayout.sectionInset = NSEdgeInsets.init(top: 16, left: 16, bottom: 16, right: 18)
        flowLayout.minimumLineSpacing = 0
        flowLayout.minimumInteritemSpacing = 0
        
        var collection = NSCollectionView.init()
        collection.collectionViewLayout = flowLayout    // 指定布局
        collection.isSelectable = true                  // item是否可以点击
    
        return collection
    }()
    
    private var jcRootArray = Array<JCCompany>()
    
    private var jcComyModel = JCCompany()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do view setup here.
        
        title = "企业管理"
        
        view.addSubview(jcSplitView)
        
        jcSplitView.addSubview(jcLeftView)
        jcSplitView.addSubview(jcRightView)
        
        jcLeftView.addSubview(jcLeftScrView)
        jcLeftView.addSubview(jcTypeComboBox)
        jcLeftView.addSubview(jcStateComboBox)
        
        jcRightView.addSubview(jcRightScrView)
        
        jcLeftScrView.documentView = rootabelview
        jcRightScrView.documentView = jcCollectionView
        
        let colum1 = NSTableColumn.init(identifier: NSUserInterfaceItemIdentifier(rawValue: "columnFrist"))
        colum1.title = ""
        colum1.width = 300
        rootabelview.addTableColumn(colum1)
        
        jcCollectionView.delegate = self
        jcCollectionView.dataSource = self
        jcCollectionView.register(JCComyImgCollectionItem.self, forItemWithIdentifier: NSUserInterfaceItemIdentifier(rawValue: "JCComyImgCollectionItem"))
        jcCollectionView.register(JCComyTextCollectionItem.self, forItemWithIdentifier: NSUserInterfaceItemIdentifier(rawValue: "JCComyTextCollectionItem"))
        
        let jcAccBtn = NSButton.init(title: "驳回申请", target: self, action: #selector(jcBtnAcction))
        jcAccBtn.setButtonType(NSButton.ButtonType.momentaryLight)
        jcAccBtn.frame = NSRect.init(x: 140, y: 20, width: 180, height: 60)
        jcAccBtn.bezelStyle = NSButton.BezelStyle.regularSquare
        jcAccBtn.tag = 100
        
        let jcNoBtn = NSButton.init(title: "同意申请", target: self, action: #selector(jcBtnAcction))
        jcNoBtn.setButtonType(NSButton.ButtonType.momentaryLight)
        jcNoBtn.frame = NSRect.init(x: 400, y: 20, width: 180, height: 60)
        jcNoBtn.bezelStyle = NSButton.BezelStyle.regularSquare
        jcNoBtn.tag = 101
    
        jcRightView.addSubview(jcAccBtn)
        jcRightView.addSubview(jcNoBtn)
        
        jcLoadData()
    }
    
    @objc private func jcBtnAcction(_ btn:NSButton){
        
        if btn.tag == 101 {
            jcTypeAcction(self.jcComyModel.company_id, type: 1)
        }else{
            jcTypeAcction(self.jcComyModel.company_id, type: 0)
        }
        
    }
    
    //  MARK:  加载审核列表数据
    private func jcLoadData() -> Void {
        
        jcRootArray.removeAll()
        
        JCAPI.jcGetCompCerList(1,type:jcType,state:jcState, success: {
            for itme in $0{
                let model:JCCompany = JCCompany.deserialize(from: itme as? NSDictionary)!
                self.jcRootArray.append(model)
            }
            self.rootabelview.reloadData()
            
            if self.jcRootArray.count > 0{
                self.jcComyModel = self.jcRootArray[0]
            }
            self.jcCollectionView.reloadData()
            
        }) {_,_ in
            
        }
    }
    //    MARK:处理操作
    private func jcTypeAcction(_ cid:String,type:Int) -> Void {
        
        let jcParameters = ["Token":JCUserModel.share().Token,
                            "Companyid":cid,
                            "CerType":"\(type)"]
        
        JCNetWork.post(JC_BASE_URL + "fixCerCompany", parameters: jcParameters, successs: { (jsonData) in
            let jcJson = JSON.init(jsonData)
            
            let alert = NSAlert.init()
            alert.addButton(withTitle: "确定")
            alert.messageText = "系统提示"
            alert.alertStyle = NSAlert.Style.informational
            
            if jcJson["Code"].intValue == 200 {
                if type == 1{
                    alert.informativeText = "您已经同意该企业认证"
                }else{
                    alert.informativeText = "您已经驳回该企业认证"
                }
            }else{
                alert.informativeText = jcJson["CodeString"].stringValue
            }
            
            alert.beginSheetModal(for: self.view.window!, completionHandler: {_ in
                self.jcLoadData()
            })
            
        }) { (error) in
          
        }
    }
}
//MARK:NSSplitViewDelegate
extension JCCamyListViewController:NSSplitViewDelegate{
    
    
    func splitView(_ splitView: NSSplitView, constrainMaxCoordinate proposedMaximumPosition: CGFloat, ofSubviewAt dividerIndex: Int) -> CGFloat {
        if dividerIndex == 0 {
            return 300
        }else{
            return CGFloat(MAXFLOAT)
        }
    }
    
    func splitView(_ splitView: NSSplitView, constrainMinCoordinate proposedMinimumPosition: CGFloat, ofSubviewAt dividerIndex: Int) -> CGFloat{
        if dividerIndex == 0 {
            return 300
        }else{
            return 200
        }
    }
    
}

extension JCCamyListViewController:NSComboBoxDelegate{
    
    func comboBoxSelectionDidChange(_ notification: Notification) {
        let jcView:NSComboBox = notification.object as! NSComboBox
        
        
        if jcView.tag == 100 {
            print("=============",jcView.indexOfSelectedItem)
            
            jcType = jcView.indexOfSelectedItem + 1
        }
        
        if jcView.tag == 101{
            print("-------------",jcView.indexOfSelectedItem)
            jcState = jcView.indexOfSelectedItem
        }
        
        jcLoadData()
    }
    
    func comboBoxSelectionIsChanging(_ notification: Notification) {
//        let jcView:NSComboBox = notification.object as! NSComboBox
//        print("===2222222222222222==========",jcView.indexOfSelectedItem)
    }
    
   
}


//MARK:NSTableView 代理方法
extension JCCamyListViewController:NSTableViewDelegate,NSTableViewDataSource{
 
    func numberOfRows(in tableView: NSTableView) -> Int {
        return jcRootArray.count
    }
    
    func tableView(_ tableView: NSTableView, shouldSelectRow row: Int) -> Bool {
        return true
    }
    
//    func tableView(_ tableView: NSTableView, objectValueFor tableColumn: NSTableColumn?, row: Int) -> Any? {
//        return "aaaaaaaaaaa"
//    }
    //MARK:自定义cell
    func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
        
        var cell:JCComyCellView? = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier.init("columnFrist"), owner: self) as? JCComyCellView
        if cell == nil {
            cell = JCComyCellView.init(frame: CGRect.init(x: 0, y: 0, width: self.view.bounds.size.width, height: 60))
            cell?.identifier = NSUserInterfaceItemIdentifier(rawValue: "columnFrist")
        }
        cell?.setData(jcRootArray[row])
        return cell!
    }
    //
    func tableView(_ tableView: NSTableView, rowViewForRow row: Int) -> NSTableRowView? {
        var rowView:NSTableRowView? = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier.init("RowView"), owner: self) as? NSTableRowView
        if rowView == nil {
            rowView = NSTableRowView.init()
            rowView?.identifier = NSUserInterfaceItemIdentifier(rawValue: "RowView")
        }
        
        rowView?.backgroundColor = NSColor.red
        
        return rowView
    }
    
//
//    func tableViewSelectionDidChange(_ notification: Notification) {
//
//    }
    
    func tableViewSelectionDidChange(_ notification: Notification) {
        let tableview:NSTableView = notification.object as! NSTableView
        print("======",tableview.selectedRow)
        
        if tableview.selectedRow >= 0 {
            self.jcComyModel = jcRootArray[tableview.selectedRow]
            self.jcCollectionView.reloadData()
        }
        
    }
        
}


//MARK: NSCollectionView 代理方法
extension JCCamyListViewController: NSCollectionViewDataSource, NSCollectionViewDelegate {
    
    func numberOfSections(in collectionView: NSCollectionView) -> Int {
        return 2
    }
    // 返回Item个数
    func collectionView(_ collectionView: NSCollectionView, numberOfItemsInSection section: Int) -> Int {
        if section == 0 {
            return 5
        }else{
            return 3
        }
    }
   
    func collectionView(_ collectionView: NSCollectionView, itemForRepresentedObjectAt indexPath: IndexPath) -> NSCollectionViewItem {
        
        if indexPath.section == 0 {
            let item:JCComyTextCollectionItem = collectionView.makeItem(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "JCComyTextCollectionItem"), for: indexPath) as! JCComyTextCollectionItem
            
            if indexPath.item == 0{
                item.jcTextView.stringValue = "企业名称：" + self.jcComyModel.company_name
            }
            if indexPath.item == 1{
                item.jcTextView.stringValue = "组织机构代码：" + self.jcComyModel.company_num
            }
            if indexPath.item == 2{
                item.jcTextView.stringValue = "法人姓名：" + self.jcComyModel.company_userName
            }
            if indexPath.item == 3{
                item.jcTextView.stringValue = "法人身份证号码：" + self.jcComyModel.company_IDCard
            }
            if indexPath.item == 4{
                item.jcTextView.stringValue = "提交审核时间：" + self.jcComyModel.company_time
            }
            
            return item
            
        }else{
            
            let item:JCComyImgCollectionItem = collectionView.makeItem(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "JCComyImgCollectionItem"), for: indexPath) as! JCComyImgCollectionItem
            
            if indexPath.item == 0{
                item.jcTextView.stringValue = "法人身份证正面"
                
                let url = URL.init(string: self.jcComyModel.img1)
                if let url = url{
                    item.jcImageView.kf.setImage(with: url)
                }
                
            }
            if indexPath.item == 1{
                item.jcTextView.stringValue = "法人身份证反面"
                
                let url = URL.init(string: self.jcComyModel.img2)
                if let url = url{
                    item.jcImageView.kf.setImage(with: url)
                }
                
            }
            if indexPath.item == 2{
                item.jcTextView.stringValue = "企业营业执照"
                
                let url = URL.init(string: self.jcComyModel.img3)
                if let url = url{
                    item.jcImageView.kf.setImage(with: url)
                }
            }
            
            
            return item
        }
        
        
    }
    // 点击方法
    func collectionView(_ collectionView: NSCollectionView, didSelectItemsAt indexPaths: Set<IndexPath>) {
        
//        let indexPath = indexPaths.first
//        print(indexPath)
        
    }
    
}
// NSCollectionView的布局方法
extension JCCamyListViewController: NSCollectionViewDelegateFlowLayout {
    // 返回Item的size
    func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> NSSize {
        
        if indexPath.section == 0 {
            return NSSize.init(width: 350, height: 50)
        }else{
            return NSSize.init(width: 350, height: 260)
        }
    }
    
    func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        if section == 0 {
            return 0
        }else{
            return 10
        }
    }
    
    func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat{
        if section == 0 {
            return 0
        }else{
            return 10
        }
    }
}


